<?php
/**
 *@fileName Utils.php 工具类
 *@FileName Utils.php   工具通用函数类
 **/
//调用需要添加config.php引用
define("DS",DIRECTORY_SEPARATOR);
class Utils {
	/**
	 * curl_post方法
	 *
	 */
	static function curl_post($url, $data) {
		$curl = curl_init($url);
		curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 30);
		curl_setopt($curl, CURLOPT_TIMEOUT, 10);
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
		curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($curl, CURLOPT_POST, 1);
		//发送一个常规的Post请求
		curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
		//Post提交的数据包
		$rv = curl_exec($curl);
		//输出内容
		curl_close($curl);
		return $rv;
	}

	/**
	 * curl_get方法
	 *
	 */
	static function curl_get($url) {
		$curl = curl_init($url);
		curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 30);
		curl_setopt($curl, CURLOPT_TIMEOUT, 10);
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
		curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
		$rv = curl_exec($curl);
		//输出内容
		curl_close($curl);

		return $rv;
	}

	static function curl_post_ssl($url, $vars, $second = 30, $aHeader = array()) {
		$ch = curl_init();
		//超时时间
		curl_setopt($ch, CURLOPT_TIMEOUT, $second);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		//这里设置代理，如果有的话
		//curl_setopt($ch,CURLOPT_PROXY, '10.206.30.98');
		//curl_setopt($ch,CURLOPT_PROXYPORT, 8080);
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

		//以下两种方式需选择一种
		//第一种方法，cert 与 key 分别属于两个.pem文件
		curl_setopt($ch, CURLOPT_SSLCERT, getcwd() . DS . 'cert' . DS . 'apiclient_cert.pem');
		curl_setopt($ch, CURLOPT_SSLKEY, getcwd() . DS . 'cert' . DS . 'apiclient_key.pem');
		curl_setopt($ch, CURLOPT_CAINFO, getcwd() . DS . 'cert' . DS . 'rootca.pem');
		//第二种方式，两个文件合成一个.pem文件
		//curl_setopt($ch,CURLOPT_SSLCERT,getcwd().'/all.pem');

		if (count($aHeader) >= 1) {
			curl_setopt($ch, CURLOPT_HTTPHEADER, $aHeader);
		}

		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $vars);
		$data = curl_exec($ch);
		if ($data) {
			curl_close($ch);
			return $data;
		} else {
			$error = curl_errno($ch);
			echo "call faild, errorCode:$error\n";
			curl_close($ch);
			return false;
		}
	}

	/**
	 *
	 *
	 * @param toURL
	 * @param paras
	 * @return
	 */
	function genAllUrl($toURL, $paras) {
		$allUrl = null;
		if (null == $toURL) {
			die("toURL is null");
		}
		if (strripos($toURL, "?") == "") {
			$allUrl = $toURL . "?" . $paras;
		} else {
			$allUrl = $toURL . "&" . $paras;
		}

		return $allUrl;
	}

	/**
	 *
	 *
	 * @param src
	 * @param token
	 * @return
	 */
	function splitParaStr($src, $token) {
		$resMap = array();
		$items = explode($token, $src);
		foreach ($items as $item) {
			$paraAndValue = explode("=", $item);
			if ($paraAndValue != "") {
				$resMap[$paraAndValue[0]] = $parameterValue[1];
			}
		}
		return $resMap;
	}

	/**
	 * trim
	 *
	 * @param value
	 * @return
	 */
	static function trimString($value) {
		$ret = null;
		if (null != $value) {
			$ret = $value;
			if (strlen($ret) == 0) {
				$ret = null;
			}
		}
		return $ret;
	}

	function formatQueryParaMap($paraMap, $urlencode) {
		$buff = "";
		ksort($paraMap);
		foreach ($paraMap as $k => $v) {
			if (null != $v && "null" != $v && "sign" != $k) {
				if ($urlencode) {
					$v = urlencode($v);
				}
				$buff .= $k . "=" . $v . "&";
			}
		}
		$reqPar;
		if (strlen($buff) > 0) {
			$reqPar = substr($buff, 0, strlen($buff) - 1);
		}
		return $reqPar;
	}

	function formatBizQueryParaMap($paraMap, $urlencode) {
		$buff = "";
		ksort($paraMap);
		foreach ($paraMap as $k => $v) {
			//	if (null != $v && "null" != $v && "sign" != $k) {
			if ($urlencode) {
				$v = urlencode($v);
			}
			$buff .= strtolower($k) . "=" . $v . "&";
			//}
		}
		$reqPar;
		if (strlen($buff) > 0) {
			$reqPar = substr($buff, 0, strlen($buff) - 1);
		}
		return $reqPar;
	}

	/**
	 * @description 获取随机字符串，默认长度为16
	 */
	static function random_str($length = 16) {
		$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
		$str = "";
		for ($i = 0; $i < $length; $i++) {
			$str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
			//$str .= $chars[ mt_rand(0, strlen($chars) - 1) ];
		}
		return $str;
	}

	/**
	 * @description 获取指定范围的随机数 ,默认为0到1之间
	 * @param {$min} 最小值
	 * @param {$max} 最大值
	 */
	static function random_int($min = 0, $max = 1) {
		srand((double)microtime() * 1000000);
		return rand($min, $max);
	}

	/**
	 * @description 获取指定位数的随机数
	 * @param {$length} 随机数长度，默认为4位
	 */
	static function generate_code($length = 4) {
		srand((double)microtime() * 1000000);
		return rand(pow(10, ($length - 1)), pow(10, $length) - 1);
	}

	/**
	 * @description 设置参数值
	 * @param {$key} 参数名称
	 * @param {$value} 参数值
	 * @param {$time} 保存期限
	 */
	static function set_session($key, $value, $time) {
		session_start();
		//使用SESSION前必须调用该函数。
		$_SESSION[$key] = $value;
		//注册一个SESSION变量
		$_SESSION['time'] = $time || time();
	}

	/**
	 * @description 获取session值
	 * @param {$key} 获取参数名称
	 */
	static function get_session($key) {
		if ($_SESSION) {
			return $_SESSION[$key];
		}
		return "";
	}

	static function arrayToXml($arr) {
		$xml = "<xml>";
		foreach ($arr as $key => $val) {
			if (is_numeric($val)) {
				$xml .= "<" . $key . ">" . $val . "</" . $key . ">";

			} else {
				$xml .= "<" . $key . "><![CDATA[" . $val . "]]></" . $key . ">";
			}
		}
		$xml .= "</xml>";
		return $xml;
	}

	/*static function json_encode_characterset($arr) {
	 //convmap since 0x80 char codes so it takes all multibyte codes (above ASCII 127). So such characters are being "hidden" from normal json_encoding
	 array_walk_recursive($arr, function(&$item, $key) {
	 if (is_string($item))
	 $item = mb_encode_numericentity($item, array(0x80, 0xffff, 0, 0xffff), 'UTF-8');
	 });
	 return mb_decode_numericentity(json_encode($arr), array(0x80, 0xffff, 0, 0xffff), 'UTF-8');

	 }*/
	static function characet($data) {
		if (!empty($data)) {
			$fileType = mb_detect_encoding($data, array('UTF-8', 'GBK', 'LATIN1', 'BIG5'));
			if ($fileType != 'UTF-8') {
				$data = mb_convert_encoding($data, 'utf-8', $fileType);
			}
		}
		return $data;
	}

	static function set_music_json($data) {
		$fp = fopen("common/music.json", "w+");
		//以读写的方式打开文件，将文件指针指向文件头并将文件大小截为零，如果文件不存在就自动创建
		//print_r('{['.implode("],[ ", $data).']}');
		//fwrite($fp, json_encode($data));
		//$jsonData=iconv("utf-8","GB2312",utf8_encode('{['.implode("],[ ", $data).']}'));
		//$jsonData=utf8_encode('{['.implode("],[ ", $data).']}');
		//$jsonData = '' . implode(",", $data) . '';
		//$jsonData=Utils::json_encode_characterset($data);
		//$jsonData = json_encode(iconv("GB2312", "UTF-8//IGNORE", $data), JSON_UNESCAPED_UNICODE);
		//$jsonData = Utils::characet(json_encode($data));
		$jsonData = json_encode($data);
		fwrite($fp, $jsonData);
		fclose($fp);
	}

	static function mb_pathinfo($filepath) {
		preg_match('%^(.*?)[\\\\/]*(([^/\\\\]*?)(\.([^\.\\\\/]+?)|))[\\\\/\.]*$%im', $filepath, $m);
		if ($m[1])
			$ret['dirname'] = $m[1];
		if ($m[2])
			$ret['basename'] = $m[2];
		if (count($m) > 5 && $m[5])
			$ret['extension'] = $m[5];
		if ($m[3])
			$ret['filename'] = $m[3];
		return $ret;
	}

	static function get_music_list() {
		$hostdir = 'resource/music';
		//获取本文件目录的文件夹地址
		$filesnames = scandir('./' . $hostdir);
		$musicArr = array();

		//获取也就是扫描文件夹内的文件及文件夹名存入数组 $filesnames
		foreach ($filesnames as $name) {
			//$pathinfo = pathinfo($hostdir . '/' . $name);
			$pathinfo = Utils::mb_pathinfo($hostdir . '/' . $name);
			if (!empty($pathinfo['extension'])) {
				//文件名统一格式规定：歌曲名_专辑_歌手
				$musicFileName = explode('_', $pathinfo['filename']);
				$music['Title'] = urlencode(mb_convert_encoding("$musicFileName[0]", "UTF-8", "GB2312"));
				$music['Description'] = urlencode(mb_convert_encoding("$musicFileName[1]&#x4E13;&#x8F91;:$musicFileName[2]", "UTF-8", "GB2312"));
				$music['MusicUrl'] = urlencode(mb_convert_encoding(SERVER_IP . "$hostdir/$name", "UTF-8", "GB2312"));
				array_push($musicArr, $music);
			}
			/*if (!empty($pathinfo['extension'])) {
			 print_r($name);
			 print_r("<br />");
			 print_r($pathinfo);
			 print_r("<br />");
			 }*/
		}
		return $musicArr;
	}

	static function get_music_json() {
		$data = json_decode(file_get_contents("common/music.json"));
		return $data;
	}

}
?>